package com.personal.dataanalyse.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.personal.core.utils.FileUtil;

/**
 * 序列化拷贝
 * @author cuibo
 *
 */
public class DeepCopyUtil
{
	private DeepCopyUtil()
	{
		
	}
	
    /**
     * 序列化深拷贝
     * @param source
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    public static <T> T deepCopy(T source) throws IOException, ClassNotFoundException
    {
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try
        {
            if (source == null)
            {
                return null;
            }
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(new BufferedOutputStream(bos));
            out.writeObject(source);
            out.flush();

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            in = new ObjectInputStream(new BufferedInputStream(bis));
            Object obj = in.readObject();
            if (obj == null)
            {
                return null;
            }
            return (T) obj;
        } finally
        {
            FileUtil.release(in);
            FileUtil.release(out);
        }
    }
}
